package com.neusoft.databus.core.repository.impl;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.databus.common.model.Metric;
import com.neusoft.databus.common.model.QMetric;
import com.neusoft.databus.common.model.QMetricGroup;
import com.neusoft.databus.core.repository.CustomizedMetricRepository;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.JPAExpressions;
import com.querydsl.jpa.impl.JPAQuery;

/**
 * @author naxiang
 */
public class CustomizedMetricRepositoryImpl extends AbstractRepository implements CustomizedMetricRepository {

    @Override
    public Page<Metric> search(Pageable pageable, Searchable searchable) {
        final QMetric qMetric = QMetric.metric;
        final JPAQuery<Metric> query = this.query().selectFrom(qMetric);
        final BooleanBuilder where = this.buildWhere(query, searchable);
        query.where(where);
        return super.search(query, pageable);
    }

    @Override
    public List<Metric> search(Searchable searchable) {
        final QMetric qMetric = QMetric.metric;
        final JPAQuery<Metric> query = this.query().selectFrom(qMetric);
        final BooleanBuilder where = this.buildWhere(query, searchable);
        query.where(where);
        return query.fetch();
    }

    @Override
    protected Class<?> getModelClass() {
        return Metric.class;
    }

    private BooleanBuilder buildWhere(JPAQuery<Metric> query, Searchable searchable) {
        final QMetric qMetric = QMetric.metric;
        final QMetricGroup qMetricGroup = QMetricGroup.metricGroup;
        final BooleanBuilder where = new BooleanBuilder();
        where.and(super.containsStr(qMetric.name, searchable, "name"));
        where.and(super.containsStr(qMetric.code, searchable, "code"));
        where.and(super.containsStr(qMetric.variable, searchable, "variable"));

        if (searchable.hasKey("metricGroup") && (null != searchable.getStrValue("metricGroup"))) {
            final BooleanBuilder orMetricGroup = new BooleanBuilder();
            orMetricGroup.or(qMetricGroup.code.containsIgnoreCase(searchable.getStrValue("metricGroup")))
                    .or(qMetricGroup.name.containsIgnoreCase(searchable.getStrValue("metricGroup")));

            where.and(qMetric.id
                    .in(JPAExpressions.select(qMetric.id).from(qMetricGroup)
                            .leftJoin(qMetricGroup.metrics, qMetric)
                            .where(orMetricGroup)));
        }

        if (searchable.hasKey("unusage") && (searchable.getBooleanValue("unusage"))) {
            where.and(qMetric.groups.isEmpty());
        }
        return where;
    }

}
